#!D:\Python27\python.exe
# -*- coding: utf-8 -*-
'''
    Login Request Command

    :copyright: (c) 2014 by Duxin.
'''

import cgi
import Cookie
import os
import hashlib

import command
import app
import sessions
from db.db_manager import UserDAO, User
from exception import ParameterError

class Login(command.Command):
    '''
        If the hash value of password + random_num equals to the password parameter, 
        puts user object into current session and return success. Otherwise, return failed.
    '''
    
    def is_param_right(self):  
        self.username = self.get_param('username')
        if self.username == None:
            raise ParameterError('error_用户名不能为空')
        
        self.password = self.get_param('password')
        if self.password == None:
            raise ParameterError('error_密码不能为空')

    def execute(self):
        user = UserDAO.find_by_username(self.username)
        
        if user:
            session = self.get_session();
            ran = session.get_attribute('random_num')
            password = hashlib.md5("%s%d"%(user.password, ran)).hexdigest()
        
            if self.password == password:
                session.set_attribute('user',  user)
                return "success"
       
        return "error_用户名密码不正确"

app.App.start(Login())
